package graph.parts;

import static ogl.vecmathimp.FactoryDefault.vecmath;
import static org.lwjgl.opengl.GL20.glUseProgram;

import java.util.LinkedList;

import org.lwjgl.opengl.GL11;

import graph.Main;
import graph.Part;
import ogl.app.Texture;
import ogl.vecmath.Vector;
import ogl.vecmathimp.MatrixImp;
import shader.Shader;

public class ShaderNode extends Group {
	private Shader shader;
	private Texture texture;
	private Vector ka = vecmath.vector(0.005f, 0.005f, 0f);
	private Vector ks = vecmath.vector(0.8f, 0.8f, 0.8f);
	private Float ke = 1000f;

	/**
	 * Gruppenknoten. Benutzt den übergeben Shader und die übergebene Textur.
	 * Der Root-Knote muss IMMER ein ShaderNode sein (damit der defaultShader gesetzt ist)
	 * @param shader
	 * @param texture
	 */
	public ShaderNode(Shader shader, Texture texture) {
		parts = new LinkedList<Part>();
		matrix = (MatrixImp) MatrixImp.identity;
		this.shader = shader;
		this.texture = texture;
	}
	
	public ShaderNode(Shader shader, Texture texture, Vector ka, Vector ks, float ke) {
		parts = new LinkedList<Part>();
		matrix = (MatrixImp) MatrixImp.identity;
		this.shader = shader;
		this.texture = texture;
		
		this.ka = ka;
		this.ks = ks;
		this.ke = ke;
	}

	@Override
	public void draw(MatrixImp m) {
		for (Part p : parts) {
			// Activate the shader program and set the transformation matrices to
			// the uniform variables.
			int program = shader.getProgram();
			glUseProgram(program);
			childrenUseShader(shader);
			
			// Nachdem der Shader aktiviert wurde, müssen alle Uniforms neu zugewiesen werden
			shader.setProjectionMatrixUniform(Main.getProjectionMatrix());
			shader.setViewMatrixUniform(Main.getViewMatrix());
			shader.addTime(Main.getElapsed());
			shader.setLightPosition(Main.getScene().findLight().getPosition());
			shader.setPhongParams(ka, ks, ke);
			
			// Bind the texture
			texture.bind();
			
			// Draw the part with the texture and shader
			p.draw((MatrixImp) matrix.mult(m));
		}
	}

}
